/*
 * @Description:地图 几何坐标
 * @Version: 2.0
 * @Author: zhao
 * @Date: 2022-06-17 09:27:12
 * @LastEditors: zhao
 * @LastEditTime: 2022-07-07 09:03:19
 */
import {
  getMapJson,
  getDivision,
  GetPointsFromMappableUnit,
  GetResultFromPoints,
  GetPointsFromShpFile,
  GetPointsFromShpTxt,
  GetMappableUnitFromType,
} from '@/api/map'
import axios from 'axios'
import { view } from "ol/layer"
const state = {
  map: null,
  tiandiMap: null,
  mapData: {},//地图相关数据
  geometryData: null,//地图几何图形数据
  mapList: [],
  SourceVec: null,//标注点实例
  markerLayer: null,//图层实例
  mapSearch: {},//地图查询
  boundaryLayer: null,//行政边界 几何 描点处
  geometryLayer: null, //几何 描点处
  GeoJSONLayer: null, //行政图层实例
  drawSource: null, //绘制图形实例
  workAreaSourceLayer: null,//
  // Layer: null, //几何 描点处
  MapJson: {},
  geometryCoordinate: [],//几何坐标
  form: {},//map查询条件
  isLeft: false,//是否点击左侧查询
  selectType: "first",//查询类型 ：行政区划:first、图幅号:second、坐标:third
  pageType: '',//页面跳转类型
  overlayForm: null,//弹窗
  tk: "579cbafd290f72fb69ef5319e2bd149c"
}
const key = {
  map: 'map',
  SourceVec: 'SourceVec'
}
const mutations = {

  setStorage_map(state, value) {
    state.map = value
    sessionStorage.setItem(key.map, JSON.stringify(value))
  },
  removeStorage_map(state) {
    state.map = null
    sessionStorage.removeItem(key.map)
  },


  setStorage_SourceVec(state, value) {
    state.SourceVec = value

    // let cache = [];
    // function stringifyCircularHandler(key, value) {
    //   if (typeof value === 'object' && value !== null) {
    //     if (cache.indexOf(value) !== -1) {
    //       // Circular reference found, discard key
    //       return;
    //     }
    //     // Store value in our collection
    //     cache.push(value);
    //   }
    //   return value;
    // };
    // sessionStorage.setItem(key.SourceVec, JSON.stringify(value, stringifyCircularHandler))

  },
  removeStorage_SourceVec(state) {
    state.SourceVec = null
    sessionStorage.removeItem(key.SourceVec)
  },
  empty(state) { //清除全部图形
    state.selectType = "no"
    if (state.geometryLayer != null) { //消除几何点

      state.geometryLayer.clear()
    }
    if (state.boundaryLayer != null) { //消除行政区域 

      state.boundaryLayer.clear()
    }
    if (state.drawSource != null) { //消除绘制图形 

      state.drawSource.clear()
    }
    if (state.workAreaSourceLayer != null) { //消除绘制图形 

      state.workAreaSourceLayer.clear()
    }
    if (state.overlayForm != null) { //消除弹窗

      state.overlayForm.setPosition(undefined)
    }

    state.GeoJSONLayer && state.map.removeLayer(state.GeoJSONLayer)
  },
  //自适应缩放级别
  selfAdaptionZoom(state, layer) {
    const VectorLayer = layer.getSource().getFeatures()[0].getGeometry().getExtent()
    if (!VectorLayer[0]) return
    state.map.getView().fit(VectorLayer);
  }

}

const actions = {
  getMapJson({ state, commit }, data) {

    return new Promise((resolve, reject) => {
      axios({
        method: "GET",
        headers: {},
        // url: "https://geo.datav.aliyun.com/areas_v3/bound/" + data + ".json",
        // url: "http://api.tianditu.gov.cn/administrative?postStr={'searchWord':156" + data + ",'searchType':0,'needSubInfo': true, 'needAll': true, 'needPolygon': true, 'needPre': true}&tk=9c70b9de519e9bb6c44f648c4a339d8c"
        url: "https://restapi.amap.com/v3/config/district?keywords=" + data + "&subdistrict=2&extensions=all&key=" + state.tk
      }).then(res => {
        resolve(res)
      })

      // var httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
      // httpRequest.open('GET', "https://geo.datav.aliyun.com/areas_v3/bound/" + data + ".json", true);//第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      // httpRequest.send();//第三步：发送请求  将请求参数写在URL中
      // /**
      //  * 获取数据后的处理程序
      //  */
      // httpRequest.onreadystatechange = function () {
      //   if (httpRequest.readyState == 4 && httpRequest.status == 200) {
      //     var json = httpRequest.responseText;//获取到json字符串，还需解析
      //     console.log(json);
      //     resolve(json)
      //   }
      // };



    })
  },
  //获取行政区划
  getDivision({ commit }, data) {
    return new Promise((resolve, reject) => {
      getDivision(data).then(res => {
        resolve(res)
      }).catch(error => {

        reject(error)
      })

    })
  },
  //根据查询条件获取对应案卷信息 
  getResultFromPoints({ commit }, data) {
    return new Promise((resolve, reject) => {
      GetResultFromPoints(data).then(res => {
        resolve(res)
      }).catch(error => {

        reject(error)
      })


    })
  },
  //根据shp文件获取对应点位信息
  getPointsFromShpFile({ commit }, data) {
    return new Promise((resolve, reject) => {
      GetPointsFromShpFile(data).then(res => {
        resolve(res)
      }).catch(error => {

        reject(error)
      })

    })
  },
  //根据图幅号获取对应点位信息
  getPointsFromMappableUnit({ commit }, data) {
    return new Promise((resolve, reject) => {

      GetPointsFromMappableUnit(data).then(res => {
        resolve(res)
      }).catch(error => {

        reject(error)
      })

    })
  },
  getPointsFromShpTxt({ commit }, data) {
    return new Promise((resolve, reject) => {

      GetPointsFromShpTxt(data).then(res => {
        resolve(res)
      }).catch(error => {

        reject(error)
      })

    })
  },
  //逆地理编码查询
  getGeoCode({ commit }, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: "GET",
        headers: {

        },
        url: "http://api.tianditu.gov.cn/geocoder?postStr={'lon':" + data[0] + ",'lat':" + data[1] + ",'ver':1}&type=geocode&tk=9c70b9de519e9bb6c44f648c4a339d8c",

      }).then(res => {

        resolve(res)
      })


    })
  },
  //图幅号数据
  getMappableUnitFromType({ commit }, data) {

    return new Promise((resolve, reject) => {
      GetMappableUnitFromType(data).then(res => {
        resolve(res)
      }).catch(error => {

        reject(error)
      })
    })
  },
}
const getters = {
  GET_MAP(state) {
    if (!state.map) {
      state.map = JSON.parse(sessionStorage.getItem(key.map))
    }
    return state.map
  },
  GET_SOURCEVEC(state) {
    if (!state.SourceVec) {
      state.SourceVec = JSON.parse(sessionStorage.getItem(key.SourceVec))
    }

    return state.SourceVec
  },
}
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}
